﻿function formatMask(field, evt, format) {
    evt = getEvent(evt);
    var key = getKeyCode(evt);
    if (!validKey(key))
        return;
    var result = "";
    var maskIdx = format.length - 1;
    var error = false;
    var _value = field.value;
    var posFinal = false;
    if (field.setSelectionRange) {
        if (field.selectionStart == _value.length)
            finalPos = true;
    }
    _value = _value.replace(/[^0123456789Xx]/g, '');
    for (var valIdx = _value.length - 1; valIdx >= 0 && maskIdx >= 0; --maskIdx) {
        var chr = _value.charAt(valIdx);
        var chrMask = format.charAt(maskIdx);
        switch (chrMask) {
            case '#':
                if (!(/\d/.test(chr)))
                    error = true;
                result = chr + result;
                --valIdx;
                break;
            case '@':
                result = chr + result;
                --valIdx;
                break;
            default:
                result = chrMask + result;
        }
    }
    field.value = result;
    field.style.color = error ? 'red' : '';
    if (finalPos) {
        field.selectionStart = result.length;
        field.selectionEnd = result.length;
    }
    return result;
}


function formatValue(field, evt)
{
 //1.000.000,00
 var xPos = CursorPosition(field);
 evt = getEvent(evt);
 var key= getKeyCode(evt);
 if (!validKey(key))
  return;
 vr = field.value = filterNumbers(filterField(field));
 if (vr.length > 0)
 {
  vr = parseFloat(vr.toString()).toString();
  _lenght = vr.length;

  if (_lenght == 1)
   field.value = "0,0" + vr;
  if (_lenght == 2)
   field.value = "0," + vr;
  if ((_lenght > 2) && (_lenght <= 5))
  {
   field.value = vr.substr(0, _lenght - 2) + ',' + vr.substr(_lenght - 2, _lenght);
  }
  if ((_lenght >= 6) && (_lenght <= 8))
  {
   field.value = vr.substr(0, _lenght - 5) + '.' + vr.substr(_lenght - 5, 3) + ',' + vr.substr(_lenght - 2, _lenght);
  }
  if ((_lenght >= 9) && (_lenght <= 11))
  {
   field.value = vr.substr(0, _lenght - 8) + '.' + vr.substr(_lenght - 8, 3) + '.' + vr.substr(_lenght - 5, 3) + ',' + vr.substr(_lenght - 2, _lenght);
  }
  if ((_lenght >= 12) && (_lenght <= 14))
  {
   field.value = vr.substr(0, _lenght - 11) + '.' + vr.substr(_lenght - 11, 3) + '.' + vr.substr(_lenght - 8, 3) + '.' + vr.substr(_lenght - 5, 3) + ',' + vr.substr(_lenght - 2, _lenght);
  }
  if ((_lenght >= 15) && (_lenght <= 18))
  {
   field.value = vr.substr(0, _lenght - 14) + '.' + vr.substr(_lenght - 14, 3) + '.' + vr.substr(_lenght - 11, 3) + '.' + vr.substr(_lenght - 8, 3) + '.' + vr.substr(_lenght - 5, 3) + ',' + vr.substr(_lenght - 2, _lenght);
  }
 }
 moveCursor(field, xPos);
}

//DD/MM/YYYY
function formatDate(field, evt)
{
 var xPos = CursorPosition(field);
 //dd/MM/yyyy
 evt = getEvent(evt);
 var key = getKeyCode(evt);
 if (!validKey(key))
  return;
 vr = field.value = filterNumbers(filterField(field));
 _lenght = vr.length;
 if (_lenght >= 2 && _lenght < 4)
  field.value = vr.substr(0, 2) + '/' + vr.substr(2);
 if (_lenght == 4)
  field.value = vr.substr(0, 2) + '/' + vr.substr(2, 2) + '/';
 if (_lenght > 4)
  field.value = vr.substr(0, 2) + '/' + vr.substr(2, 2) + '/' + vr.substr(4);
 moveCursor(field, xPos);
}

function CursorPosition(textarea)
{
 var pos = 0;
 if (typeof (document.selection) != 'undefined')
 {
  //IE
  var range = document.selection.createRange();
  var i = 0;
  for (i = textarea.value.length; i > 0; i--)
  {
   if (range.moveStart('character', 1) == 0)
    break;
  }
  pos = i;
 }
 if (typeof (textarea.selectionStart) != 'undefined')
 {
  //FireFox
  pos = textarea.selectionStart;
 }
 if (pos == textarea.value.length)
  return 0; //retorna 0 quando não precisa posicionar o elemento
 else
  return pos; //posição do cursor
}

// move o cursor para a posição pos
function moveCursor(textarea, pos)
{
 if (pos <= 0)
  return; //se a posição for 0 não reposiciona

 if (typeof (document.selection) != 'undefined')
 {
  //IE
  var oRange = textarea.createTextRange();
  var LENGTH = 1;
  var STARTINDEX = pos;

  oRange.moveStart("character", -textarea.value.length);
  oRange.moveEnd("character", -textarea.value.length);
  oRange.moveStart("character", pos);
  //oRange.moveEnd("character", pos);
  oRange.select();
  textarea.focus();
 }
 if (typeof (textarea.selectionStart) != 'undefined')
 {
  //FireFox
  textarea.selectionStart = pos;
  textarea.selectionEnd = pos;
 }
}

function formatInteger(field, evt)
{
 //1234567890
 xPos = CursorPosition(field);
 evt = getEvent(evt);
 var key = getKeyCode(evt);
 if (!validKey(key))
  return;
 field.value = filterNumbers(filterField(field));
 moveCursor(field, xPos);
}

function filterField(field)
{
 var s = "";
 var cp = "";
 vr = field.value;
 _lenght = vr.length;
 for (i = 0; i < _lenght; i++)
 {
  if (vr.substring(i, i + 1) != "/"
            && vr.substring(i, i + 1) != "-"
            && vr.substring(i, i + 1) != "."
            && vr.substring(i, i + 1) != "("
            && vr.substring(i, i + 1) != ")"
            && vr.substring(i, i + 1) != ":"
            && vr.substring(i, i + 1) != ",")
  {
   s = s + vr.substring(i, i + 1);
  }
 }
 return s;
 //return campo.value.replace("/", "").replace("-", "").replace(".", "").replace(",", "")
}

function filterNumbers(field)
{
 var s = "";
 var cp = "";
 vr = field;
 _lenght = vr.length;
 for (i = 0; i < _lenght; i++)
 {
  if (vr.substring(i, i + 1) == "0" ||
            vr.substring(i, i + 1) == "1" ||
            vr.substring(i, i + 1) == "2" ||
            vr.substring(i, i + 1) == "3" ||
            vr.substring(i, i + 1) == "4" ||
            vr.substring(i, i + 1) == "5" ||
            vr.substring(i, i + 1) == "6" ||
            vr.substring(i, i + 1) == "7" ||
            vr.substring(i, i + 1) == "8" ||
            vr.substring(i, i + 1) == "9")
  {
   s = s + vr.substring(i, i + 1);
  }
 }
 return s;
 //return campo.value.replace("/", "").replace("-", "").replace(".", "").replace(",", "")
}

function filterNumbersWithComma(field)
{
 var s = "";
 var cp = "";
 vr = field;
 _lenght = vr.length;
 var complement = 0; //flag paga contar o número de virgulas
 for (i = 0; i < _lenght; i++)
 {
  if ((vr.substring(i, i + 1) == "," && complement == 0 && s != "") ||
            vr.substring(i, i + 1) == "0" ||
            vr.substring(i, i + 1) == "1" ||
            vr.substring(i, i + 1) == "2" ||
            vr.substring(i, i + 1) == "3" ||
            vr.substring(i, i + 1) == "4" ||
            vr.substring(i, i + 1) == "5" ||
            vr.substring(i, i + 1) == "6" ||
            vr.substring(i, i + 1) == "7" ||
            vr.substring(i, i + 1) == "8" ||
            vr.substring(i, i + 1) == "9")
  {
   if (vr.substring(i, i + 1) == ",")
    complement = complement + 1;
   s = s + vr.substring(i, i + 1);
  }
 }
 return s;
}

function formatCNPJ(field, evt)
{
 //99.999.999/9999-99
 var xPos = CursorPosition(field);
 evt = getEvent(evt);
 var key = getKeyCode(evt);
 if (!validKey(key))
  return;
 vr = field.value = filterNumbers(filterField(field));
 _lenght = vr.length;
 if (_lenght >= 2 && _lenght < 5)
  field.value = vr.substr(0, 2) + '.' + vr.substr(2);
 else if (_lenght >= 5 && _lenght < 8)
  field.value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '.' + vr.substr(5);
 else if (_lenght >= 8 && _lenght < 12)
  field.value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '.' + vr.substr(5, 3) + '/' + vr.substr(8);
 else if (_lenght >= 12)
  field.value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '.' + vr.substr(5, 3) + '/' + vr.substr(8, 4) + '-' + vr.substr(12);
 moveCursor(field, xPos);
}

function formatCPF(field, evt)
{
 //999.999.999-99
 var xPos = CursorPosition(field);
 evt = getEvent(evt);
 var key = getKeyCode(evt);
 if (!validKey(key))
  return;
 vr = field.value = filterNumbers(filterField(field));
 _lenght = vr.length;
 if (_lenght >= 3 && _lenght < 6)
  field.value = vr.substr(0, 3) + '.' + vr.substr(3);
 else if (_lenght >= 6 && _lenght < 9)
  field.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.' + vr.substr(6);
 else if (_lenght >= 9)
  field.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.' + vr.substr(6, 3) + '-' + vr.substr(9);
 moveCursor(field, xPos);
}

function formatDouble(field, evt)
{
 //18,53012
 var xPos = CursorPosition(field);
 evt = getEvent(evt);
 var key = getKeyCode(evt);
 if (!validKey(key))
  return;
 field.value = filterNumbersWithComma(field.value);
 moveCursor(field, xPos);
}

function formatTelephone(field, evt)
{
 //(00) 0000-0000
 var xPos = CursorPosition(field);
 evt = getEvent(evt);
 var key = getKeyCode(evt);
 if (!validKey(key))
  return;
 vr = field.value = filterNumbers(filterField(field));
 tam = vr.length;
 if (tam == 1)
  field.value = '(' + vr;
 else if (tam >= 2 && tam < 6)
  field.value = '(' + vr.substr(0, 2) + ') ' + vr.substr(2);
 else if (tam >= 6)
  field.value = '(' + vr.substr(0, 2) + ') ' + vr.substr(2, 4) + '-' + vr.substr(6);
 //(
 //    if(xPos == 1 || xPos == 3 || xPos == 5 || xPos == 9)
 //        xPos = xPos +1
 moveCursor(field, xPos);
}

function formatCEP(field, evt)
{
 //312555-650
 var xPos = CursorPosition(field);
 evt = getEvent(evt);
 var key = getKeyCode(evt);
 if (!validKey(key))
  return;
 vr = field.value = filterNumbers(filterField(field));
 _lenght = vr.length;
 if (_lenght < 5)
  field.value = vr;
 else if (_lenght == 5)
  field.value = vr + '-';
 else if (_lenght > 5)
  field.value = vr.substr(0, 5) + '-' + vr.substr(5);
 moveCursor(field, xPos);
}

function validKey(key)
{
 if (key == 8 //backspace
 //Esta evitando o post, quando são pressionadas estas teclas.
 //Foi comentado pois, se for utilizado o evento texchange, é necessario o post.
        || key == 9 //TAB
        || key == 27 //ESC
        || key == 16 //Shif TAB 
        || key == 45 //insert
        || key == 46 //delete
        || key == 35 //home
        || key == 36 //end
        || key == 37 //esquerda
        || key == 38 //cima
        || key == 39 //direita
        || key == 40)//baixo
  return false;
 else
  return true;
}

function getEvent(evt)
{
 if (!evt) evt = window.event; //IE
 return evt;
}

function getKeyCode(evt)
{
 var code;
 if (typeof (evt.keyCode) == 'number')
  code = evt.keyCode;
 else if (typeof (evt.which) == 'number')
  code = evt.which;
 else if (typeof (evt.charCode) == 'number')
  code = evt.charCode;
 else
  return 0;
 return code;
}